from socket import *
from sys import *
from threading import *

HOST = '127.0.0.1'
PORT = 12345

print "Entrez votre pseudo :"
nick = raw_input()

class ThreadReception(Thread):
#Gestion de la reception des messages#
    def __init__(self, connexion):
        Thread.__init__(self)
        self.connexion = connexion #Socket de connexion

    def run(self):
        message_recu = self.connexion.recv(1024)
        #if ... == connecter
        print "*" + message_recu + "*"
        while 1:
            message_recu = self.connexion.recv(1024)
            print "*" + message_recu + "*"
            if message_recu.upper() == nick + ': /QUIT' or message_recu == "":
                break
            #Fin du thread de rÃ©ception
        #Forcer la fermueture du thread
        th_R._Thread__stop()
        print "Client arrÃªtÃ©, connexion imterrompue"
        self.connexion.close()
        
class ThreadEmission(Thread):
#Emission de messages
    def __init__(self, conn):
        Thread.__init__(self)
        self.connexion = conn #socket de connexion
        
    def run(self):
        while 1:
            message_emis = raw_input()
            if message_emis != "":
                self.connexion.send(message_emis)
    #Emission terminÃ©e

#Thread Principal
connexion = socket(AF_INET, SOCK_STREAM)
#Connexion au serveur :
try:
    connexion.connect((HOST, PORT))
except socket:
    print "La connexion a echouÃ©e"
    sys.exit()
print "Connexion Ã©tablie !"
connexion.send("nickname" + nick) #connexion.send(nick + " vient de se connecter !")

#Lancement des threads
th_E = ThreadEmission(connexion)
th_R = ThreadReception(connexion)
th_E.start()
th_R.start()
 